import { _decorator, Color, Component, instantiate, Label, Node, NodePool, Prefab, Sprite, tween, UIOpacity, Vec3 } from 'cc';
import { TxDian } from './TxDian';
const { ccclass, property } = _decorator;

@ccclass('EffectManager')
export class EffectManager {

    // public createDianPool(){
    //     this.dianPool = new NodePool();
    // }
    static _instance: EffectManager;
    static get instance() {
        if (this._instance == null) {
            this._instance = new EffectManager();
        }
        return this._instance;
    }

    dianPool: NodePool = new NodePool();
    init() {

    }
    /** 创建节点 */
    createDian(pos: any, touchType: any, nodeDian: Node, prefab: Prefab) {
        let dian = null;
        if (this.dianPool.size() > 0) {
            dian = this.dianPool.get();
        } else {
            dian = instantiate(prefab);
        }
        nodeDian.addChild(dian);

        if (touchType == 'start') {
            dian.setSiblingIndex(2);
            dian.getComponent(TxDian).init_1(pos);
        } else if (touchType == 'end') {
            dian.setSiblingIndex(3);
            dian.getComponent(TxDian).init_2(pos);
        }
    }

    /** 清理所有Tx点 */
    cleanAllTXDian(nodeDian: Node) {
        var children = nodeDian.children;
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(TxDian)
            if (js) {
                this.onDianKilled(children[i])
            }
        }
    }

    /** 杀死不需要的Tx点（将其放入对象池） */
    onDianKilled(dian: Node) {
        this.dianPool.put(dian);
    }

    setRandomBgColor(bg: Sprite, arrColorBg: { r: number, g: number, b: number }[]) {
        var i_random = Math.floor(Math.random() * 6)
        const targetColor = new Color(arrColorBg[i_random].r, arrColorBg[i_random].g, arrColorBg[i_random].b);
        tween(bg)
            .to(0.5, { color: targetColor })
            .start();

    }

    scoreEffect(tx_score: Label, addScore: number, x: number, y: number) {
        // 播放上飘分数
        tx_score.string = '+' + addScore;
        tx_score.node.getComponent(UIOpacity).opacity = 255;
        tx_score.node.setPosition(new Vec3(x, y + 100));
        tween(tx_score.node).by(1, { position: new Vec3(0, 100, 0) }).start();
        tween(tx_score.node.getComponent(UIOpacity)).to(1, { opacity: 0 }).start();
    }

    guangQuanEffect(tx_guangQuan:Node,x: number, y: number) {
        tx_guangQuan.setPosition(new Vec3(x, y + 20));
        tx_guangQuan.getComponent(UIOpacity).opacity = 255;
        tx_guangQuan.scale = Vec3.ONE;
        tween(tx_guangQuan).to(0.5, { scale: new Vec3(5, 2, 1) }).start();
        tween(tx_guangQuan.getComponent(UIOpacity)).to(0.5, { opacity: 0 }).start();
    }
}


